<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $noNeedRight = ['clsss'];

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $dataLimit = 'auth';
    protected $adminIds = '';

    public function _initialize()
    {
        parent::_initialize();
        if ($this->auth->getGroupIds()[0] == 8) {
            $this->adminIds = '*';
        }
        $this->model = model('User');
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), '1', ['class' => 'form-control selectpicker']));
        $this->assignconfig('username', $this->auth->check('user/username'));
        $this->assignconfig('nickname', $this->auth->check('user/nickname'));
        $this->assignconfig('mobile', $this->auth->check('user/mobile'));
        $this->assignconfig('class', $this->auth->check('user/class'));
        $this->assignconfig('money', $this->auth->check('user/money'));
        $this->assignconfig('discount_amount', $this->auth->check('user/discount_amount'));
        $this->assignconfig('gender', $this->auth->check('user/gender'));
        $this->assignconfig('status', $this->auth->check('user/status'));

        $this->assignconfig('recharge', $this->auth->check('user/user/recharge'));
        $this->assignconfig('leave', $this->auth->check('user/user/leave'));
        $this->assignconfig('info', $this->auth->check('user/user/info'));
        $this->assignconfig('purchase', $this->auth->check('user/user/purchase'));
        $this->assignconfig('translate', $this->auth->check('school_class/translate'));

        $this->assignconfig('unboundx', $this->auth->check('user/user/unbound'));


    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_class = [];
            if ($class_id = $this->request->request('class_id')) {
                $class_user = model('SchoolCalssUser');
                $clss_user_list = $class_user->where('class_id', $class_id)->select();
                $user_ids = array_column($clss_user_list, 'user_id');
                $where_class['user.id'] = ['in', $user_ids];
            }
            $total = $this->model
                ->with(['group'])
                ->where($where)
                ->where($where_class)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with(['group'])
                ->where($where)
                ->where($where_class)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            //echo('123456');



            $list = collection($list)->toArray();
            foreach ($list as $k => $v) {
                // $v->hidden(['password', 'salt']);
                $school_class_user = db('school_calss_user')->where('status', '0')->where('user_id', $v['id'])->select();


                $school_class = db('school_class')->where('id', 'in', array_column($school_class_user, 'class_id'))->select();
                //print_r($school_class);
                $list[$k]['school_class']['class_name'] = implode(',', array_column($school_class, 'class_name')) ? implode(',', array_column($school_class, 'class_name')) : '-';
                $list[$k]['school_class']['is_weixin'] = db('third')->where('user_id', $v['id'])->find() ? true : false;
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $class_id = $this->request->request('class_id', '0');
        $this->assignconfig('user', ['class_id' => $class_id]);
        $this->assign('class_id', $class_id);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 班级添加
     */
    public function class_add()
    {
        $class_id = $this->request->request('class_id', 0);
        if ($this->request->isPost()) {
            $user_ids = $this->request->request();
            model('school_calss_user')->where('class_id', $class_id)->delete();

            $data = [];
            if ($user_ids['class_list']) {
                foreach ($user_ids['class_list'] as $id) {
                    $data[] = [
                        'user_id' => $id,
                        'class_id' => $class_id
                    ];
                }
                model('school_calss_user')->insertAll($data);
            }
            model('school_class')->where('id', $class_id)->update(['number' => count($data)]);
            $this->success();
        }
        $class_user_list = model('school_calss_user')->field('user_id')->where('class_id', $class_id)->select();
        $class_user_list = array_column($class_user_list, 'user_id');
        $class_1 = db('user')->field('id,nickname')->where('id', 'in', $class_user_list)->select();
        $class_2 = db('user')->field('id,nickname')->where('id', 'notin', $class_user_list)->select();
        $this->assignconfig('classlist', ['class_1' => $class_1, 'class_2' => $class_2]);
        return $this->fetch();
    }

    /**
     * 充值缴费
     * @return bool
     */
    public function recharge()
    {

        if ($this->request->isPost()) {
            $id = input('ids');
            $remarks = $this->request->request('remarks');
            $value = $this->request->request('value');
            if (!is_numeric($value)) {
                $this->error('请输入正确的数字');
            }
            $user = new \app\common\model\User();
            $user->money($value, $id, '充值缴费' . '(' . $remarks . ')');
            $dataLog = [];
            $dataLog[] = [
                'admin_id' => $this->auth->id,
                'user_id' => $id,
                'create_time' => time(),
                'content' => '充值缴费' . $value . '元' . '(' . $remarks . ')'
            ];
            $SchoolUserLog = model('SchoolUserLog');
            $SchoolUserLog->insertAll($dataLog);
            $this->success('充值成功');
        }
        return $this->fetch();

    }

    /**
     * 请假
     */
    public function leave()
    {

        if ($this->request->isPost()) {
            $p = $this->request->request('row/a');
            $schedule = db('school_class_subject_schedule')
                ->alias('a')
                ->field('a.*,b.subject_name')
                ->join('ed_school_class_subject c', 'c.id = a.class_subject_id')
                ->join('ed_school_subject b', 'b.id = c.subject_id')
                ->where('a.id', $p['id'])
                ->find();
            $datas = db('school_user_attendance_sheet')
                ->where('user_id', $p['user_id'])
                ->where('subject_schedule_id', $p['id'])
                ->find();
            if ($datas) {
                db('school_user_attendance_sheet')->where('id', $datas['id'])->update(['status' => '3', 'remark' => $p['remark'], 'createtime' => time()]);
                db('school_calss_user')
                    ->where('class_id', $schedule['class_id'])
                    ->where('user_id', $p['user_id'])
                    ->setDec('use_class_hour');
                $dataLog = [
                    'admin_id' => $this->auth->id,
                    'user_id' => $p['user_id'],
                    'create_time' => time(),
                    'content' => '补假' . $schedule['subject_name'] . '(' . $schedule['date'] . ' ' . $schedule['time_slot'] . ')退回课时1'
                ];
            } else {
                $dataLog = [
                    'admin_id' => $this->auth->id,
                    'user_id' => $p['user_id'],
                    'create_time' => time(),
                    'content' => '请假' . $schedule['subject_name'] . '(' . $schedule['date'] . ' ' . $schedule['time_slot'] . ')'
                ];
                $data = [
                    'user_id' => $p['user_id'],
                    'subject_schedule_id' => $schedule['id'],
                    'class_id' => $schedule['class_id'],
                    'class_subject_id' => $schedule['class_subject_id'],
                    'status' => '3',
                    'remark' => $p['remark'],
                    'createtime' => time()
                ];
                db('school_user_attendance_sheet')->insert($data);
            }
            db('SchoolUserLog')->insert($dataLog);
            $this->success('操作成功');
        }
        $ids = input('ids');
        $this->assign('ids', $ids);
        return $this->fetch();
    }

    public function clsss()
    {
        $ids = input('ids');
        $info = db('school_calss_user')
            ->alias('a')
            ->field('a.*,b.class_name,b.status')
            ->join('ed_school_class b', 'a.class_id = b.id', 'left')
            ->where('user_id', $ids)
            ->where('b.status', '0')
            ->where('a.status', '0')
            ->select();
        $data = [];
        foreach ($info as $v) {
            $name = $v['class_name'];
            $data[] = [
                'value' => $v['class_id'],
                'name' => $name
            ];
        }
        return json(['code' => 1, 'data' => $data]);
    }

    public function getleave()
    {
        $ids = $this->request->request('ids');
        $user_id = input('user_id');
        if ($ids) {
            //  $calss_user = db('school_calss_user')->where('status', '0')->where('user_id', $ids)->select();
            //  $calss_id = array_column($calss_user, 'class_id');
            $list = db('school_class_subject_schedule')->alias('a')
                ->field('a.*,c.subject_name')
                ->join('ed_school_class_subject b', 'b.id = a.class_subject_id', 'left')
                ->join('ed_school_subject c', 'c.id = b.subject_id', 'left')
                ->where('a.class_id', $ids)
                //->where('a.status', '0')
                ->order('a.date', 'asc')
                ->limit(40)
                ->select();
            $data = [];
            foreach ($list as $v) {
                $datas = db('school_user_attendance_sheet')
                    ->where('user_id', $user_id)
                    ->where('subject_schedule_id', $v['id'])
                    ->find();
                if ($v['status'] == 0) {
                    $name = $v['subject_name'] . '(' . $v['date'] . ' ' . $v['time_slot'] . ')';
                    if ($datas) {
                        if ($datas['status'] == '3') {
                            $name = $v['subject_name'] . '(' . $v['date'] . ' ' . $v['time_slot'] . ')(已请假)';
                        }
                    }
                } else {
                    if ($datas) {
                        if ($datas['status'] == '3') {
                            $name = $v['subject_name'] . '(' . $v['date'] . ' ' . $v['time_slot'] . ')(已请假)';
                        } elseif ($datas['status'] == '1') {
                            $name = $v['subject_name'] . '(' . $v['date'] . ' ' . $v['time_slot'] . ')(补假)';
                        }
                    } else {
                        continue;
                    }

                }
                $data[] = [
                    'value' => $v['id'],
                    'name' => $name
                ];
            }
            return json(['data' => $data, 'code' => 1]);
        }
    }

    /**
     * 用户详情
     */
    public function info()
    {
        $this->adminIds = '*';
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $user_id = input('user_id');
            $class_where = [];
            if ($user_id) {
                $class_where['user_id'] = $user_id;
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if ($this->auth->getGroupIds()[0] == 1 || $this->auth->getGroupIds()[0] == 8) {

            }else{
                $schoolcalss_info = db('school_class')->where('admin_id', $this->auth->id)->select();
                $ciass_ids = array_column($schoolcalss_info, 'id');
                $class_where['class_id'] = ['in', $ciass_ids];
            }
            $total = model('SchoolCalssUser')
                ->where($where)
                ->where($class_where)
                ->order($sort, $order)
                ->count();

            $list = model('SchoolCalssUser')
                ->where($where)
                ->where($class_where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
          //  print_r($class_where);
            foreach ($list as $k => $v) {
                // $row->visible(['id', 'nickname', 'mobile', 'total_class_hour', 'use_class_hour', 'createtime']);
                $list[$k]['SchoolClass'] = db('SchoolClass')
                    ->field('a.*,b.total_class_hour,b.use_class_hour')
                    ->alias('a')
                    ->join('school_class_subject b', 'b.class_id = a.id')
                    ->where('a.id', $v['class_id'])
                    ->find();
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);;
            return json($result);
        }
        $user_id = input('ids');
        $this->assignconfig('user_id', $user_id);
        return $this->view->fetch();
    }

    /**
     * 解绑
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function unbound()
    {
        $ids = input('ids');
        db('third')->where('user_id', $ids)->delete();
        db('user_token')->where('user_id', $ids)->delete();
        $this->success('解绑成功');
    }

    /**
     * 购买优惠课时
     */
    public function purchase()
    {
        if ($this->request->isPost()) {
            $ids = input('ids');
            $id = $this->request->request('id');
            $auth = db('user')->where('id', $ids)->find();
            //print_r($auth);
            $package_info = db('school_discount_package')->where('id', $id)->find();
            if ($package_info['price'] > $auth['money']) {
                // $this->error('余额不足');
            }
            $user = new \app\common\model\User();
            $user->money(-$package_info['price'], $auth['id'], '购买优惠课时');
            $dataLog = [];
            $dataLog[] = [
                'admin_id' => $this->auth->id,
                'user_id' => $auth['id'],
                'create_time' => time(),
                'content' => '购买优惠课时' . $package_info['discount_value'] . '节' . '扣除余额' . $package_info['price'] . '元'
            ];
            $SchoolUserLog = model('SchoolUserLog');
            $SchoolUserLog->insertAll($dataLog);
            db('user')->where('id', $auth['id'])->update(['discount_amount' => $auth['discount_amount'] + $package_info['discount_value']]);
            $this->success('操作成功');
        }
        return $this->fetch();
    }

    /**
     * 优惠课时列表
     */
    public function purchase_list()
    {
        $discount_package_list = db('school_discount_package')->select();
        $data = [];
        foreach ($discount_package_list as $v) {
            $name = '价格：' . $v['price'] . '元，优惠课时：' . $v['discount_value'] . '节';
            $data[] = [
                'value' => $v['id'],
                'name' => $name
            ];
        }
        return json(['code' => 1, 'data' => $data]);
    }


    /**
     * 购买课室次数
     */
    public function csmmeet()
    {
        if ($this->request->isPost()) {
            $ids = input('ids');
            $id = $this->request->request('id');
            $auth = db('user')->where('id', $ids)->find();
            //print_r($auth);
            $package_info = db('csmmeet_package')->where('id', $id)->find();
            if ($package_info['price'] > $auth['money']) {
                // $this->error('余额不足');
            }
            $user = new \app\common\model\User();
            $user->money(-$package_info['price'], $auth['id'], '购买课室次数');
            $dataLog = [];
            $dataLog[] = [
                'admin_id' => $this->auth->id,
                'user_id' => $auth['id'],
                'create_time' => time(),
                'content' => '购买课室次数' . $package_info['discount_num'] . '次' . '扣除余额' . $package_info['price'] . '元'
            ];
            $SchoolUserLog = model('SchoolUserLog');
            $SchoolUserLog->insertAll($dataLog);
            db('user')->where('id', $auth['id'])->update(['csmmeet' => $auth['csmmeet'] + $package_info['discount_num']]);
            $this->success('操作成功');
        }
        return $this->fetch();
    }

    /**
     * 优惠课时列表
     */
    public function csmmeet_package_list()
    {
        $discount_package_list = db('csmmeet_package')->select();
        $data = [];
        foreach ($discount_package_list as $v) {
            $name = '价格：' . $v['price'] . '元，课室：' . $v['discount_num'] . '次';
            $data[] = [
                'value' => $v['id'],
                'name' => $name
            ];
        }
        return json(['code' => 1, 'data' => $data]);
    }

}
